package com.jdchain.samples.rest.controller;

import com.jdchain.samples.rest.dto.ApiResponse;
import com.jdchain.samples.rest.dto.SetKeyValueRequest;
import com.jdchain.samples.rest.service.ContractService;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

/**
 * 合约 RESTful API 控制器
 */
@RestController
@RequestMapping("/api/contract")
@CrossOrigin(origins = "*")
public class ContractController {

    private static final Logger logger = LoggerFactory.getLogger(ContractController.class);

    @Autowired
    private ContractService contractService;

    /**
     * 设置键值对
     *
     * @param request 设置键值对请求
     * @return API 响应
     */
    @PostMapping("/set")
    public ApiResponse<String> setKeyValue(@RequestBody SetKeyValueRequest request) {
        try {
            logger.info("收到设置键值对请求: key={}, value={}", request.getKey(), request.getValue());

            if (request.getKey() == null || request.getKey().trim().isEmpty()) {
                return ApiResponse.error("键不能为空");
            }

            if (request.getValue() == null) {
                return ApiResponse.error("值不能为空");
            }

            String txHash = contractService.setKeyValue(request.getKey(), request.getValue());
            return ApiResponse.success("设置成功", txHash);

        } catch (Exception e) {
            logger.error("设置键值对失败", e);
            return ApiResponse.error("设置失败: " + e.getMessage());
        }
    }

    /**
     * 获取键对应的值
     *
     * @param key 键
     * @return API 响应
     */
    @GetMapping("/get/{key}")
    public ApiResponse<String> getValue(@PathVariable String key) {
        try {
            logger.info("收到获取键值请求: key={}", key);

            if (key == null || key.trim().isEmpty()) {
                return ApiResponse.error("键不能为空");
            }

            String value = contractService.getValueByTransaction(key);
            return ApiResponse.success(value);

        } catch (Exception e) {
            logger.error("获取键值失败", e);
            return ApiResponse.error("获取失败: " + e.getMessage());
        }
    }

    /**
     * 健康检查接口
     *
     * @return API 响应
     */
    @GetMapping("/")
    public ApiResponse<String> health() {
        return ApiResponse.success("服务正常运行");
    }
}

